﻿using Application.Common.Interfaces;
using Application.Features.Roles.DTOs;
using Application.Features.Roles.Specifications;
using AutoMapper;
using Common.Models;
using Common.Extensions;
using Domain.Entities;
using MediatR;
using System.ComponentModel;
using System.Linq.Dynamic.Core;
using System.Text.Json.Serialization;
using Common.Attributes;


namespace Application.Features.Roles.Queries.Pagination;

/// <summary>
/// 分页查询角色数据
/// </summary>
[Description("分页查询")]
[GroupDescription(("角色管理"))]
public class RolesWithPaginationQuery : RoleAdvancedFilter, IRequest<PaginatedData<RoleOutput>>
{
    public override string ToString()
    {
        return $"Search:{Keyword},RoleName:{RoleName},RoleCode:{RoleCode},IsActive:{IsActive} {OrderBy}, {SortDirection}, {PageNumber}, {PageSize}";

    }

    [JsonIgnore]
    public RoleAdvancedPaginationSpec Specification => new RoleAdvancedPaginationSpec(this);
}

public class RolesWithPaginationQueryHandler :
         IRequestHandler<RolesWithPaginationQuery, PaginatedData<RoleOutput>>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public RolesWithPaginationQueryHandler(
        IApplicationDbContext context,
        IMapper mapper
        )
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<PaginatedData<RoleOutput>> Handle(RolesWithPaginationQuery request, CancellationToken cancellationToken)
    {
        return await _context.Roles
            .OrderBy($"{request.OrderBy} {request.SortDirection}")
            .ProjectToPaginatedDataAsync<Role, RoleOutput>(
            request.Specification,
            request.PageNumber,
            request.PageSize,
            _mapper.ConfigurationProvider,
            cancellationToken);
    }
}
